package org.grow.present.service.impl;

import org.grow.present.service.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * @Author: xwg
 * @CreateDate: 2023/9/20
 */

@Service
public class RedisCodeGenerator implements CodeGenerator {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //      SHS20230605000001
    @Override
    public String nextCode(String prefix) {
        String header = null;
        String body = null;
        String footer = null;
        if (prefix == null) {
//            default
            header = "DFT";
        } else if (prefix.length() > 3) {
            header = prefix.substring(0, 3).toUpperCase(Locale.ROOT);
        } else {
            header = prefix.toUpperCase(Locale.ROOT);
        }
//        System.out.println(header);
        body = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        System.out.println(body);

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String headerKey = "CODE:" + header;
//        setnx "" 0
        ops.setIfAbsent(headerKey, "1");
        String current = ops.get(headerKey);
        ops.increment(headerKey);

//        System.out.println(current);
        footer = String.format("%06d", Integer.parseInt(current));
//        System.out.println(footer);
        return header + body + footer;
    }
}
